﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;

public partial class TaoBaoApi_TB_BBLink : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Page.Theme = BLL.Common.GetWSMThemes();
    }
    private static string _sqlBB;
    private static string _sqlSP;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            new TBCommon().BindTBShop(ddlShop);
           
            _sqlBB = "select mid,bbmc,field2,field1 from tb_baobei order by mid desc";
            BindBB(_sqlBB);
            _sqlSP = "select spdm ,spmc from shangpin order by spdm desc";
            BindProduct(_sqlSP);
            BindBBCheck();
        }
    }
    void BindBBCheck()
    {
        ddlBBChecked.Items.Clear();
        ddlBBChecked.Items.Add("未关联");
        ddlBBChecked.Items.Add("已关联");
        ddlBBChecked.Items.Add("全部");
        ddlBBChecked.SelectedIndex = 2;
    }
    //绑定宝贝
    void BindBB(string sql)
    {
        if (sql == null)
            sql = "select mid,bbmc,field2,field1 from tb_baobei order by mid desc";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        gvBB.DataSource = ds.Tables[0];
        gvBB.DataBind();
    }
    protected string GetLinkStatus(object o)
    {
        if(o is DBNull || o==null||o.ToString().Length==0||o.ToString().ToLower()=="null")
            return "<font color=gray>未关联</font>";
        return "<font color=green><b>已关联</b></font>";
    }
    void BindProduct(string sql)
    {
        if (sql == null)
            sql = "select spdm ,spmc from shangpin order by spdm desc";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        gvSP.DataSource = ds.Tables[0];
        gvSP.DataBind();        
    }
    protected string GetSPLinkStatus(object o)
    {
        if (o is DBNull || o == null || o.ToString().Length == 0)
            return null;
        string sql = "select count(*) from tb_baobei where field2='" + o.ToString() + "'";
        if (DBUtility.SqlHelper.ExecuteCountSql(DBUtility.SqlHelper.LocalSqlServer, sql) > 0)
            return "<font color=green><b>已关联</b></font>";
        return "<font color=gray>未关联</font>";
    }
    protected void btnBind_Click(object sender, EventArgs e)
    {
        int c = 0;
        string proCode = null;
        foreach (GridViewRow row in gvSP.Rows)
        {
            CheckBox chk = (CheckBox)row.FindControl("chkOne");
            if (chk != null && chk.Checked)
            {
                c++;
                proCode = row.Cells[1].Text;
            }
        }
        if (c==0||c>1)
        {
            new TBCommon().ShowMessage(Page, "一次只能且必须选择一个商品。");
            return;
        }
        List<int> midList = new List<int>();
        foreach (GridViewRow row in gvBB.Rows)
        {
            CheckBox chk = (CheckBox)row.FindControl("chkOne");
            if (chk != null && chk.Checked)
                midList.Add(Convert.ToInt32(row.Cells[1].Text));
        }
        if (midList.Count == 0)
        {
            new TBCommon().ShowMessage(Page, "请至少选择一个宝贝。");
            return;
        }
        foreach(int mid in midList)
            UpdateTBBaobei(mid, proCode);
        Response.Redirect(Request.RawUrl);
    }
    void UpdateTBBaobei(int mid,string code)
    {
        if (mid > 0&&code!=null)
        {
            Model.TaoBao.TB_BAOBEI bb = new BLL.TaoBao.TB_BAOBEI().GetModel(mid);
            if (bb != null)
            {
                bb.field2 = code;
                new BLL.TaoBao.TB_BAOBEI().Update(bb);
            }
        }
    }
    protected void gvSP_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvSP.PageIndex = e.NewPageIndex;
        BindProduct(_sqlSP);
    }
    protected void gvSP_RowCreated(object sender, GridViewRowEventArgs e)
    {
        new TBCommon().gv_RowCreated(sender, e, gvSP, Page);
    }
    protected void gvBB_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvBB.PageIndex = e.NewPageIndex;
        BindBB(_sqlBB);
    }
    protected void gvBB_RowCreated(object sender, GridViewRowEventArgs e)
    {
        new TBCommon().gv_RowCreated(sender, e, gvBB, Page);
    }
    protected void chkAll_OnCheckedChanged(object sender, EventArgs e)
    {
        new TBCommon().chk_OnCheckedChanged(sender, e, gvBB, "chkOne");
    }
    //查询商品
    protected void btnSpSearch_Click(object sender, EventArgs e)
    {
        _sqlSP = "select spdm ,spmc from shangpin order by spdm desc";
        if (txtSPMC.Text.Trim().Length > 0)
            _sqlSP = "select spdm,spmc from shangpin where spmc like '%" + txtSPMC.Text + "%'";
        BindProduct(_sqlSP);
    }
    // 查询宝贝
    protected void btnBBSearch_Click(object sender, EventArgs e)
    {
        _sqlBB = "select mid,bbmc,field2,field1 from tb_baobei where";
        if (ddlShop.SelectedIndex > -1)
        {
            int pid = new TBCommon().GetShopIdByZH(ddlShop.SelectedItem.Text);
            if (pid > 0)
                _sqlBB += " pid=" + pid+" and";
        }
        if (txtBB.Text.Trim().Length > 0)
        {
            _sqlBB += " bbmc like '%" + txtBB.Text + "%' and";
        }
        if (ddlBBChecked.SelectedIndex == 0)
            _sqlBB += " field2 is NULL";
        if (ddlBBChecked.SelectedIndex == 1)
            _sqlBB += " field2 is not NULL";
        if (ddlBBChecked.SelectedIndex == 2)
            if (_sqlBB.EndsWith("and"))
                _sqlBB = _sqlBB.Substring(0, _sqlBB.Length - 3);
        BindBB(_sqlBB);
    }
    //显示当前商品的关联明细
    protected void btnShow_Click(object sender, EventArgs e)
    {
        List<string> SPDM = new List<string>();
        foreach (GridViewRow row in gvSP.Rows)
        {
            CheckBox chk = (CheckBox)row.FindControl("chkOne");
            if (chk != null && chk.Checked)
                SPDM.Add(row.Cells[1].Text);
        }
        if (SPDM.Count == 0)
        {
            new TBCommon().ShowMessage(Page, "请选择一个商品。");
            return;
        }
        string spdmList = "'";
        foreach (string s in SPDM)
            spdmList += s + "','";
        spdmList = spdmList.Substring(0, spdmList.Length - 2);
        string sql = "select field1,bbmc from tb_baobei where field2 in (" + spdmList + ")";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        gvBB2.DataSource = ds.Tables[0];
        gvBB2.DataBind();
    }
    struct MidGuid
    {
        public int Mid;
        public string Guid;
    }
    //自动关联所选
    protected void btnLinkSelected_Click(object sender, EventArgs e)
    {       
        List<MidGuid> mgList = new List<MidGuid>();       
        foreach (GridViewRow row in gvBB.Rows)
        {
            CheckBox chk = (CheckBox)row.FindControl("chkOne");
            if (chk != null && chk.Checked)
            {
                TextBox txt = (TextBox)row.FindControl("txtGuid");
                if (txt != null)
                {
                    MidGuid mg = new MidGuid();
                    mg.Mid = Convert.ToInt32(row.Cells[1].Text);
                    mg.Guid = txt.Text;
                    mgList.Add(mg);
                }
            }
        }
        if (mgList.Count == 0)
        {
            new TBCommon().ShowMessage(Page, "请至少选择一个宝贝。");            
            return;
        }
        int ret = DoLinkBB(mgList);
        new TBCommon().ShowMessage(Page, "此次共成功关联商品个数：" + ret.ToString());        
    }
    int DoLinkBB(List<MidGuid> mgList)
    {
        int c = 0;
        foreach (MidGuid mg in mgList)
        {
            string spdm = GetHuoHaobyGuid(mg.Guid);
            if (spdm == null)
                continue;
            if (new BLL.SHANGPIN().GetModel(spdm)==null)
                continue;
            UpdateTBBaobei(mg.Mid, spdm);
            c++;
        }
        return c;
    }
    string GetHuoHaobyGuid(string guid)
    {
        try
        {
            string spdm = null;
            string url = "http://item.taobao.com/auction/item_detail.jhtml?item_id="+guid;
            HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            Stream myStream = myResponse.GetResponseStream();
            string html = new StreamReader(myStream, System.Text.Encoding.GetEncoding("GB2312")).ReadToEnd();
            myStream.Close();
            Regex r1 = new Regex("<li title=\"货号\">货号:([^<]*)</li>", RegexOptions.IgnoreCase);
            Match m = r1.Match(html);
            if (m.Success)
                spdm = m.Groups[1].ToString().Trim();
            return spdm;
        }
        catch
        {
            return null;
        }
    }
    //关联全部商品
    protected void btnLinkAll_Click(object sender, EventArgs e)
    {
        List<MidGuid> mgList = new List<MidGuid>();
        string sql = "select mid,field1 from tb_baobei where field2 is NULL ";
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            new TBCommon().ShowMessage(Page, "系统宝贝表中无数据，或者已经全部关联，不重复操作。");
            return;
        }
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            MidGuid mg = new MidGuid();
            mg.Mid = Convert.ToInt32(ds.Tables[0].Rows[i][0]);
            mg.Guid = ds.Tables[0].Rows[i][1].ToString();
            mgList.Add(mg);
        }
        int ret = DoLinkBB(mgList);
        new TBCommon().ShowMessage(Page, "此次共成功关联商品个数：" + ret.ToString());        
    }
}
